package com.tengju.bff.interfaces.manage.crm.activity.facade;

import com.tengju.bff.interfaces.manage.crm.activity.facade.assembler.ActivityAssembler;
import com.tengju.bff.interfaces.manage.crm.activity.form.ActivityTargetSaveForm;
import com.tengju.bff.interfaces.manage.crm.activity.vo.ActivityDetailVO;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.bff.interfaces.shared.InterfaceCode;
import com.tengju.bff.interfaces.shared.InterfaceException;
import com.tengju.motivation.application.activity.ActivityApplicationService;
import com.tengju.motivation.domain.model.activity.*;
import com.tengju.motivation.domain.model.goods.Goods;
import com.tengju.motivation.domain.model.goods.GoodsRepository;
import com.tengju.motivation.domain.model.goods.GoodsType;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.tengju.user.domain.shared.ResultCodeEnum.*;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ActivityTargetManageFacade {

    private final GoodsRepository goodsRepository;
    private final ActivityRepository activityRepository;
    private final ActivityApplicationService activityApplicationService;

    public ApiResponse<ActivityDetailVO> detail(ActivityId activityId) {

        Activity activity = activityRepository.getActivityById(activityId);

        if (activity == null) {
            return null;
        }
        String validMsg = activity.checkValid();
        if (validMsg != null) {
            return ApiResponse.newFailure(ILLEGAL_OPERATE.getCode(), "活动不符合要求:" + validMsg);
        }

        List<ActivityTarget> targets = activityRepository.getTargetList(activityId);
        //活动限制的目标商品id
        List<Long> ids = new ArrayList<>();
        Optional.ofNullable(activity.getExtraInfo())
                .map(Activity.ActivityExtraInfo::getLimitGoods)
                .map(Activity.ActivityExtraInfo.LimitGoods::getGoodsList)
                .map(list -> list.stream()
                        .map(Goods::getLongId)
                        .collect(Collectors.toList()))
                .ifPresent(ids::addAll);

        GoodsType goodsType = Optional.ofNullable(activity.getExtraInfo())
                .map(Activity.ActivityExtraInfo::getLimitGoods)
                .map(Activity.ActivityExtraInfo.LimitGoods::getLimitGoodsType)
                .orElse(null);

        LimitSolution limitSolution = Optional.ofNullable(activity.getExtraInfo())
                .map(Activity.ActivityExtraInfo::getLimitGoods)
                .map(Activity.ActivityExtraInfo.LimitGoods::getLimitSolution)
                .orElse(null);

        Map<String/* GoodsId */, Goods> goodsMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(ids)) {
            goodsMap = goodsRepository.getGoods(ids, goodsType);
            if (CollectionUtils.isEmpty(goodsMap)) {
                throw new InterfaceException(InterfaceCode.BUSINESS_ERROR,
                        "配置商品：" + ids + ", 找不到对应商品");
            } else if (goodsMap.size() != ids.size()) {
                throw new InterfaceException(InterfaceCode.BUSINESS_ERROR,
                        "配置商品：" + ids + ", 仅存在商品：" + goodsMap.keySet());
            }
        }
        final Map<String/* GoodsId */, Goods> keyBrandsMap;
        //如果是指定不参与的或全部，需要列举重点品牌
        if ((limitSolution == LimitSolution.EXCLUDE && goodsType == GoodsType.BRAND)
                || limitSolution == LimitSolution.NONE) {
            keyBrandsMap = goodsRepository.getKeyBrands();
            //重点品牌中要排除指定不参与的
            goodsMap.keySet().forEach(keyBrandsMap::remove);
        } else {
            keyBrandsMap = new HashMap<>();
        }

        return ApiResponse.newSuccess(ActivityAssembler.toDetail(activity, targets, goodsMap, keyBrandsMap));
    }

    public ApiResponse<Void> save(ActivityTargetSaveForm form) {

        ActivityId activityId = ActivityId.of(form.getActivityId());
        Activity activity = activityRepository.getActivityById(activityId);

        if (activity == null) {
            return ApiResponse.newFailure(DATA_NOT_EXISTS.getCode(), "活动不存在");
        }
        if (CollectionUtils.isEmpty(form.getLimitRules())) {
            return ApiResponse.newFailure(PARAMETER_EMPTY.getCode(), "目标不能为空");
        }

        List<ActivityTarget> list = ActivityAssembler.formToDomain(activity, form);

        activityApplicationService.save(activityId, list);

        return ApiResponse.newSuccess();
    }

}
